package com.example.leetcode.leetcode.concurrent;

/**
 * @author zhuhaitao
 * @email zhuhaitao@imoran.net
 * @date 2020/8/4 11:46 上午
 */
public class Spinlock {

    public volatile int status = 0;

    public void lock() {
        while (!compareAndSet(0, 1)) {
            System.out.println("自旋。。。");
            //暂让cpu使用权
//            Thread.yield();   线程过多，使用yield，cpu执行的线程有可能一直是同一个

//            LockSupport.park();

        }
    }

    public void unlock() {
        status = 0;
    }

    private boolean compareAndSet(int except, int now) {
        if (except == status) {
            status=now;
            System.out.println(Thread.currentThread().getName()+"修改了status的值"+status);
            return true;
        } else {
            return false;
        }
    }
}
